/*
 * @Description: 连接数据库的配置
 * @Author: YaoXiaotTian
 * @Date: 2021-04-18 13:57:50
 * @LastEditors: YaoXiaoTian
 * @LastEditTime: 2021-05-02 21:55:29
 */
const mysql = require("mysql");

// 创建mysql连接，使用数据库连接池
const pool = mysql.createPool({
  host: "182.61.145.76",
  user: "root",
  password: "mysql",
  port: "3306",
  database: "travel_website",
});

/**
 * select和delete操作
 * @param  {string}   sql      sql语句
 * @param  {Function} callback 回调函数
 * @return {none}
 */
let sdQuery = function (sql, callback) {
  pool.getConnection(function (err, conn) {
    if (err) {
      console.log("CONNECT ERROR:", err.message);
      callback(err, null, null);
    } else {
      conn.query(sql, function (qerr, vals, fields) {
        //释放连接
        conn.release();
        //事件驱动回调
        console.log(qerr, vals, fields, "fields");
        callback(qerr, vals, fields);
      });
    }
  });
};

/**
 * update和insert操作
 * @param  {string}   sql      sql语句
 * @param  {array}    params   参数数组
 * @param  {Function} callback 回调函数
 * @return {none}
 */
let uiQuery = function (sql, params, callback) {
  pool.getConnection(function (err, conn) {
    if (err) {
      console.log("CONNECT ERROR:", err.message);
      callback(err, null, null);
    } else {
      conn.query(sql, params, function (qerr, vals, fields) {
        //释放连接
        conn.release();
        //事件驱动回调
        callback(qerr, vals, fields);
      });
    }
  });
};

/**
 * query函数重载
 * @return {none}
 */
exports.query = function () {
  let len = arguments.length; //获取传入的参数数量
  console.log(len, "len");
  console.log(arguments);
  if (len == 2) {
    let sql = arguments[0];
    let cb = arguments[1];
    console.log(sql, cb);
    sdQuery(sql, cb);
  } else if (len == 3) {
    let sql = arguments[0];
    let params = arguments[1];
    let cb = arguments[2];
    uiQuery(sql, params, cb);
  } else {
    console.log("ERROR:", "传参不对");
  }
};

exports.queryAsync = (sql) => {
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, conn) {
      if (err) {
        reject(err);
        console.log("出现错误1");
        console.log(err);
      } else {
        conn.query(sql, function (qerr, vals, fields) {
          if (qerr) {
            reject([qerr, null]);
            console.log("出现错误2");
            console.log(qerr);
          } else {
            resolve([null, JSON.parse(JSON.stringify(vals))]);
          }
          //释放连接
          conn.release();
        });
      }
    });
  });
};
